package pers.vic.system.system.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;

import pers.vic.base.bo.system.SysMenu;
import pers.vic.base.controller.BaseConsoleController;
import pers.vic.base.pager.CommonLookup;
import pers.vic.base.pager.Remind;
import pers.vic.system.system.service.SysMenuService;



/**
 * 菜单表
 * 
 */
@Controller
@RequestMapping("/system/menu")
public class SysMenuController extends BaseConsoleController{
	

	@Resource
	private SysMenuService sysMenuService;
	
	//重定向到当前页面的page页
	private static final String REDIRECT_CREENT_INDEX = "redirect:/common/system/menu/";
	
	//JSP页面的页面前缀路径
	private static final String JSP_PATH = "system/menu/";
	
	
    /**列表页*/
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String page(Model model) {
		List<SysMenu> tree =  sysMenuService.all();
		String treeJson = JSON.toJSONString(tree);
		model.addAttribute("treeJson", treeJson);
		return JSP_PATH + "list";
	}
	
	
	/**查询*/
	@RequestMapping(value = "/", method = RequestMethod.POST)
	public String search(CommonLookup lookup) {
		setLookup(lookup);
		return REDIRECT_CREENT_INDEX;
	}
	
	/**前往新增页面*/
	@RequestMapping( value = "/0", method = RequestMethod.GET)
	public String add(Model model){
		return JSP_PATH + "form"; 
	}
	
	/**前往修改页面*/
	@RequestMapping( value = "/{id}", method = RequestMethod.GET)
	public String editor(@PathVariable int id, Model model){
		SysMenu entity = sysMenuService.findById(id);
		model.addAttribute("entity", entity);
		return JSP_PATH + "form"; 
	}
	
	/**保存*/
	@RequestMapping( value = "/{id}", method = RequestMethod.POST)
	public String save(@PathVariable int id, SysMenu entity, RedirectAttributes attr){
		entity.setId(id);
		if(id == 0) {//to add
			sysMenuService.insert(entity);
			attr.addFlashAttribute(Remind.success());
		}else if(id > 0 ){ //to update
			sysMenuService.update(entity);
			attr.addFlashAttribute(Remind.success());
		}else {
			attr.addFlashAttribute(Remind.danger());
		}
		return REDIRECT_CREENT_INDEX;
	}
	
	/**单个删除*/
	@RequestMapping( value = "/{id}/remove", method = RequestMethod.GET)
	public String delete(@PathVariable int id, RedirectAttributes attributes){
		sysMenuService.delete(id);
		attributes.addFlashAttribute(Remind.success());
		return REDIRECT_CREENT_INDEX;
	}
	
	/**批量删除*/
	@RequestMapping( value = "/remove", method = RequestMethod.POST)
	public String batchDelete(int[] ids, RedirectAttributes attributes){
		sysMenuService.delete(ids);
		attributes.addFlashAttribute(Remind.success());
		return REDIRECT_CREENT_INDEX;
	}
	
}
